package main

import (
	"fmt"
	"go-guide/rpc/net/proto"
	"go-guide/rpc/net/tcp/constant"
	"net"
)

func main() {

	listener, err := net.Listen(constant.NetWorkType, constant.Address)

	if err != nil {
		fmt.Printf("error occurred when listen to %s, error = %v", constant.Address, err)
		return
	}

	// start for loop to accept connections
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("accept connections failed , error = %v", err)
			break
		}
		go func(conn net.Conn) {
			recvBuf := make([]byte, 1024)
			// n 表示可读的字节数
			n, err := conn.Read(recvBuf)
			if err != nil {
				fmt.Printf("read bytes error = %v", err)
				return
			}

			realRecvBytes := recvBuf[:n]

			helloRequest := &proto.HelloRequest{}
			err = helloRequest.XXX_Unmarshal(realRecvBytes)
			if err != nil {
				fmt.Printf("protobuf searial failed , error = %v", err)
				return
			}

			username := helloRequest.GetUsername()

			fmt.Printf("[Server]-> %s", username)

			response := proto.HelloResponse{
				Message: fmt.Sprintf("Hello, %s", username),
			}

			sendBytes := make([]byte, 1024)
			_, _ = response.XXX_Marshal(sendBytes, true)

			sendLen, err := conn.Write(sendBytes)
			fmt.Printf("send length %d, error = %v", sendLen, err)
		}(conn)

	}

}
